from tortoise.expressions import Q, F

from app.core.crud import CRUDBase
from app.models.exams import Result, Exam
from app.schemas.exams import ResultCreate, ResultUpdate


class ResultController(CRUDBase[Result, ResultCreate, ResultUpdate]):
    def __init__(self):
        super().__init__(model=Result)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs = await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at", "deleted_at"]) for obj in objs]

        for obj in data:
            title = await Exam.filter(id=obj["exam_id"]).first().values('title')
            obj['title'] = title['title']
        return total, data

    async def do_create(self, obj_in: ResultCreate):
        exam_id = obj_in.exam_id
        exam_data = await Exam.filter(id=exam_id).first().values("id")
        if exam_data:
            ##试卷存在
            await self.create(obj_in=obj_in)
            return True
        else:
            return False

    async def do_update(self, obj_in: ResultUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self, data_id: int):
        await self.remove(id=data_id)
        return True


result_controller = ResultController()
